import {
  _decorator,
  Camera,
  Component,
  EventHandler,
  EventTouch,
  Input,
  input,
  Node,
  NodeEventType,
  geometry,
  PhysicsSystem,
} from "cc";
const { ccclass, property, type } = _decorator;

@ccclass("NodeEvents")
export class NodeEvents extends Component {
  start() {}

  update(deltaTime: number) {}
  protected _registerNodeEvent() {
    console.log("_registerNodeEvent");
    input.on(Input.EventType.TOUCH_START, this._onTouchBegan, this);
    input.on(Input.EventType.TOUCH_END, this._onTouchEnded, this);
  }

  protected _unregisterNodeEvent() {
    console.log("_unregisterNodeEvent");
    input.off(Input.EventType.TOUCH_START, this._onTouchBegan, this);
    input.off(Input.EventType.TOUCH_END, this._onTouchEnded, this);
  }

  private _pressed: boolean;

  @property
  @type(Camera)
  private cameraCom: Camera;
  private _ray: geometry.Ray = new geometry.Ray();

  protected _onTouchBegan(event?: EventTouch) {
    this._pressed = true;
  }

  @type([EventHandler])
  @property
  public clickEvents: EventHandler[] = [];

  onEnable() {
    this._registerNodeEvent();
  }

  onDisable() {
    this._unregisterNodeEvent();
  }

  protected _onTouchEnded(event?: EventTouch) {
    console.log("_onTouchEnded");
    if (!this.enabledInHierarchy) {
      return;
    }
    if (this._pressed) {
     

      const touch = event.touch!;
      this.cameraCom.screenPointToRay(
        touch.getLocationX(),
        touch.getLocationY(),
        this._ray
      );
      if (PhysicsSystem.instance.raycast(this._ray)) {
        const raycastResults = PhysicsSystem.instance.raycastResults;
        for (let i = 0; i < raycastResults.length; i++) {
          const item = raycastResults[i];
          if (item.collider.node == this.node) {
            EventHandler.emitEvents(this.clickEvents, event);
            this.node.emit("click", this);
            break;
          }
        }
      } else {
        console.log("raycast does not hit the target node !");
      }
    }
    this._pressed = false;
    if (event) {
      event.propagationStopped = true;
    }
  }
}
